<?php
	
	/**
 	* 
 	* @param unknown_type $lang
 	* @return string
 	*/
	function changeLang($lang){
	
		$url = $_SERVER['QUERY_STRING'];
		parse_str($url, $param);
		$param[C('VAR_LANGUAGE')] = $lang;
		return '?'.http_build_query($param);
	}

	/**
	 * 函数名称：del_dir
	 * 简要描述：删除文件夹
	 */
	function del_dir($dir) {
		if (!$dh = opendir($dir)) return false;
		while (false !== ($file = readdir($dh))) {
			if ($file != "." && $file != "..") {
				$fullpath = $dir . '/' . $file;
				if (!is_dir($fullpath)) {
					if (!unlink($fullpath)) { // 删除不了，尝试修改文件权限
						chmod($fullpath, 0777);
						if (!unlink($fullpath)) {
							return false;
						} 
					} 
				} else {
					if (!del_dir($fullpath)) {
						chmod($fullpath, 0777);
						if (!del_dir($fullpath)) return false;
					} 
				} 
			} 
		} 
		closedir($dh);
		if (rmdir($dir)) {
			return true;
		} else {
			return false;
		} 
	} 
	
	/**
	 * 函数名称：randomstr
	 * 简要描述：随机字母
	 */
	function folderFilter($folder,$isurl=false) {
		//windows
		if(DIRECTORY_SEPARATOR=='\\' && !$isurl){ 
			return str_replace("/","\\",$folder);
		}else{
		//linux
			return str_replace("\\","/",$folder);
		}
	}

	/**
	 * 函数名称：randomstr
	 * 简要描述：随机字母
	 */
	function randomstr($length = '') {  
		$str = '';  
		for ($i = 0; $i < $length; $i++) {  
			$str .= chr(mt_rand(97, 122));  
		}  
		return $str;  
	}
	
	/**
	 * 函数名称：isemail
	 * 简要描述：邮箱地址合法性检查
	 */
	function isemail($val,$domain=""){
		if(!$domain) {
			if( preg_match("/^[a-z0-9-_.]+@[\da-z][\.\w-]+\.[a-z]{2,4}$/i", $val) ){
				return true;
			}
			else return false;
		}else{
			if( preg_match("/^[a-z0-9-_.]+@".$domain."$/i", $val) ){
				return true;
			}
			else return false;
		}
	}
	
	/**
	 * 函数名称：ismobile
	 * 简要描述：检查输入的是否为手机号
	 */
	function ismobile($val){
		if(preg_match("/^1[3458]\d{9}$/",$val))
			return true;
		return false;
	}
	
   //创建订单号12+5
   function createOrderNo(){
   		return date("ymd").'-'.date("Hi").'-'.rand(101,999);
   }
   
   /**
    * 根据请求参数生成签名
    */
   function createRestSign($map){
   
   		ksort($map);
   		$url = http_build_query($map);
   		return myencrypt($url);
   }
   
   /**
    * 发送rest请求
    */
   function sendRest($action, $map=array(), $method="get", $json=true){
   		
   		if(!$map['noCheckRole']){
   			if(C('USER_AUTH_CITYID')){
   				$map['city_id']     = session(C('USER_AUTH_CITYID'));
   			}
	   		if(C('USER_AUTH_KEY')){
	   			$map['addid']     = session(C('USER_AUTH_KEY'));
	   		}
	   		if(C('USER_AUTH_ROLE_VIEW')){
	   			$map['role_view'] = session(C('USER_AUTH_ROLE_VIEW'));
	   		}
	   		if(C('USER_AUTH_TIME_VIEW')){
	   			$map['time_view'] = session(C('USER_AUTH_TIME_VIEW'));
	   		}
   		}
   		
	   	$method = strtolower($method);
	   	$url    = createRestUrl($action,$map,$method);
	   	//$res  = file_get_contents($url);echo $url;
	   	$ch = curl_init($url);
		
	   	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true) ;
	   	curl_setopt($ch, CURLOPT_BINARYTRANSFER, true) ;
	   
	   	if($method == "post"){
	   		curl_setopt($ch, CURLOPT_POST, 1);
	   		curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($map));
	   	}
	   
	   	$output = curl_exec($ch);
		
	   	if($json){
			$output2 = $output;
			$output = json_decode($output,true);
			if(!$output){
				$output = json_decode(substr($output2, 3),true);
			}
	   	}

	   	return $output;
   }
   
	//缓存所有百度POI
	function mapAll($flag=false){
	
		$pois = F("MAP_POI");
		if($flag){
			$list = mapList();
			if($list['status'] === 0){
				$pois = $list["pois"];
				F("MAP_POI",$pois);
			}
		}
		return $pois ;
	}
	
	//根据条件查找对应的POI
	function mapByArray($key,$field,$flag=false){
	
		$list = mapAll($flag);
		$row  = array();
		foreach($list as $k=>$v){
			if($key == $v[$field]){
				$row[] = $v ;
			}
		}
		return $row;
	}
	
	//云检索百度POI
	function mapList($data=array()){
	
		$map['ak']  = C("MAP_AK");
		$map['geotable_id'] = C("MAP_OUTLET_ID");
		$map['page_size']   = 200;
	
		$url = C("MAP_STORGE")."list";
		$map = array_merge($map,$data);
		return curlGet($url,$map);
	}
	
	//poi周边搜索
	function mapNearby($data){
		
		if(empty($data['radius'])){
			$data['radius'] = C("MAP_RADIUS");
		}
		
		$map['ak']          = C("MAP_AK");
		$map['geotable_id'] = C("MAP_OUTLET_ID");
		$map['page_size']   = 200;
		$map['sortby']      = "distance:1";
	
		$url = C("MAP_NEARBY");
		$map = array_merge($map,$data);
		$poi = curlGet($url,$map);

		log::write('mapNearby:'.var_export($poi,true),Log::DEBUG);
		if($poi['status'] === 0){
			return $poi['contents'];
		}else{
			return false;
		}
	}
	
	//详细地址转换成百度经纬度
	function mapAddressToPoi($address){
		
		$map['ak']      = C("MAP_AK");
		$map['output']  = "json";
		$map['address'] = $address;
		
		$url = C("MAP_ADDRESSPOI");
		$poi = curlGet($url,$map);
		if($poi['status'] === 0){
			return $poi['result']['location'];
		}else{
			return false;
		}
	}
	
	//IP地址转换成百度经纬度
	function mapIpToPoi($ip){
		
		$map['ak']   = C("MAP_AK");
		$map['coor'] = "bd09ll";
		$map['ip']   = $ip;
	
		$url = C("MAP_IPPOI");
		//address_detail point
		return curlGet($url,$map);
	}
	
	//发送CURL的POST请求
	function curlPost($url,$map){
	
		import('ORG.Wechat.Snoopy');
		$snoopy = new Snoopy;
		$snoopy->set_submit_multipart();
		if ($snoopy->submit($url, $map)) {
			return json_decode($snoopy->results,true);
		}else{
			return false;
		}
	}
	
	//发送CURL的GET请求 parse_url
	function curlGet($url,$map){
	
		$url = $url."?".http_build_query($map);
	    //$res = file_get_contents($url);
		
		Log::write('curlGet2:'.var_export($url,true),Log::DEBUG);

		$ch  = curl_init($url);
		curl_setopt($ch,CURLOPT_RETURNTRANSFER,true) ;
		curl_setopt($ch,CURLOPT_BINARYTRANSFER,true) ;
		$res = curl_exec($ch);
		$result = json_decode($res,true);
		return $result;
	}
	
	//根据key读取数据字典的值
	function getDictByKey($key,$lang){
		$options = F("$key");
		if(is_array($options)){
			foreach($options as $k=>$v){
				if($v['pid']){
					$value = json_decode($v['value'],true);
					$jsjson_arr[$v['id']] = array($value[$lang],$v['pid'],$v['level']);
				}else{
					$frist_id = $v['id'];
				}
			}
		}
		return array("id"=>$frist_id,"array"=>$jsjson_arr);
	}
	
	/**
	 * 行为记录
	 */
	function behaviorEvent($type,$actionid){
		
		$maps['areaGUID']     = C("AREA_GUID");
		$maps['userGUID']     = $actionid;//cookie("memberGuestId");
		$maps['fromGUID']     = cookie("memberFromId");
		$maps['domain']       = $_SERVER['HTTP_HOST'];
		$maps['behaviorType'] = $type;
		$maps['actionId']     = $actionid;
		
		return sendRest("Behavior/view", $maps);
	}
	
	//根据id 读取字典的值
	function getDictValue($key,$id){
		
		$res   = '';
		$lang  = getLang();
		$keys  = explode(",", $key);
		$array = array();
		foreach($keys as $key){
			$value = F("Dict_Value_".$key);
			$array = array_merge($array,$value);
		}
	
		$vals  = @$value[$id];
		$res   = @$vals[$lang];
		return $res;
	}
	
	//根据id 读取缓存文件的值
	function getCacheValue($key,$id){
		$res   = '';
		$value = F($key);

		$vals  = @$value[$id];
		$res   = @$vals['title'];
		return $res;
	}

	//得到session值
	function getSession($skey,$key=''){
		$val = session(C($skey));
		if(empty($key)){
			return $val;
		}else{
			return $val[$key];
		}
	}
	
	function getCookie($skey,$key=''){
		$val = cookie(C($skey));
		if(empty($key)){
			return $val;
		}else{
			return $val[$key];
		}
	}
	
	//连接两个字符串
	function concat($str,$append){
		return $str.$append;
	}
	
	//删除文件夹下所有文件
	function deldir($dir){

		$list = scandir($dir); 
		
  		foreach($list as $file){
			$fullpath = $dir."/".$file;
			
			if($file!="." && $file!="..") {
				if(!is_dir($fullpath)) {
					unlink($fullpath);
				}else {
					deldir($fullpath);
				}
			}
		}
	}
	
	/**
	* @函数名:echoText
	* @参数:$str-需要格式化的字符串
	* @作用:input type='text' 反转义\'\" 原样输出< > " '  &
	* @返回值:字符串
	*/
	function echoText($str){
		$str = html(stripslashes($str));
		return $str;
	}
	
	/**
	* @函数名:echoTextarea
	* @参数:$str-需要格式化的字符串
	* @作用: textarea 反转义\'\" 原样输出< > " '  &
	* @返回值:字符串
	*/
	function echoTextarea($str){
		$str = html($str);//stripslashes 
		$str = str_replace("\n", " <br>", $str); 
		$str = str_replace(" ", "&nbsp;", $str);
		return $str;
	}
	
	/**
	 * @函数名:html
	 * @参数:$str-需要格式化的字符串
	 * @作用: 原样输出< > " '  &
	 * @返回值:字符串
	 */
	function html($str){
		return htmlspecialchars($str);
	}
	
	
	/**
     * 记录日志
     * @param $status   操作状态
     * @param $content  操作内容
     * @param $id       数据内容主键
     * @param $table    数据内容模型
     */
	function wlog($status=1,$content='',$id=0,$table=''){
		
	    if(C('OPEN_LOG')){
	    	
	    	$module = MODULE_NAME;
	    	$action = ACTION_NAME;
	    	$model  = M("Log");
	    	
	    	if(empty($content)){
	    		load("@.node");
	    		$nodes  = return_array($module);
	    		$actions= $nodes[$action];
	    		$content= $actions[getLang()];
	    		$table  = $module;
	    		
	    		if($status == 1){
	    			$content .= L("cfg_dtips_success");
	    		}else{
	    			$content .= L("cfg_dtips_failure");
	    		}
	    	}
	   		
	    	$data['content'] = $content;
	    	$data['status']  = $status;
	    	$data['module']  = $module;
	    	$data['action']  = $action;
	    	$data['tableid'] = $table;
	    	$data['dataid']  = $id;
	    	$data['addid']   = session(C('USER_AUTH_KEY'));
	    	$data['addtime'] = time();
	    	
	    	$model->add($data);
	    }
	}
	
	/**
	 *获取当前语言版本
	**/
	function getLang(){
		$lang_now = LANG_SET;
		if(empty($lang_now)){
			$lang_now = cookie("think_language");
			if(empty($lang_now)){
				$lang_now = C("DEFAULT_LANG");
			}
		}
		return $lang_now;
	}
	
	//获取挡墙语言版本显示的值
	function getLangVal(){
		$lang = getLang();
		$array = C('LANG_ARRAY');
		return $array[$lang];	
	}
	
	//截取指定長度字符串
	function sub_str($str, $length = 0, $append = true) {
		$str = trim($str);
		$strlength = strlen($str);
		if ($length == 0 || $length >= $strlength) {
			return $str;
		}
		elseif ($length < 0){
			$length = $strlength + $length;
			if ($length < 0){
				$length = $strlength;
			}
		}
		if (function_exists('mb_substr')) {
			$newstr = mb_substr($str, 0, $length, "utf-8");
		}
		elseif (function_exists('iconv_substr')) {
			$newstr = iconv_substr($str, 0, $length, "utf-8");
		}
		else {
			$newstr = rtrim(substr($str, 0, $length));
		}
	
		if ($append && $str != $newstr)  {
			$newstr .= '...';
		}
		return $newstr;
	}
	
	/*生成唯一標識符
	 * @sha1()函數， "安全散列算法（SHA1）"
	 * @返回的是16位的字符串
	*/
	function create_id($str='') {    
		$data = $_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR'].time().rand();    
		$data = sha1($data);    
		return $str.substr(md5(time().$data),8,16);
	}
	
	/**
	* @函数名:myencrypt
	* @参数:$str-要加密的字符串
	* @作用:混淆MD5加密函数
	* @返回值:加密后的32位MD5字符串
	*/
	function myencrypt($str){
		$str = trim($str);
		$result = '';
		if(strlen($str)>=5){
			if(@C('CONFUSE')){
				$result = md5(substr($str,5,strlen($str)).C('CONFUSE').substr($str,0,5));
			}else{
				$result = md5(substr($str,5,strlen($str)).substr($str,0,5));
			}
		}else{
			md5($str);
		}
		return $result;	
	}
	
	/**
	 * 通知用戶
	 */
	function noticeUser($key,$map){
		
		$action = "Tip/".$key;
		$json   = sendRest($action,$map);
	}
	
	
	/**
	* @函数名:escape
	* @参数:$str-需要编码的字符串
	* @作用:php实现javascript中escape函数编码
	* @返回值:编码后的字符串
	*/
	function escape($str){
		$res = @unpack("H*",iconv("utf-8","UCS-2",$str));
		$res = preg_replace("/(.{4})/is","%u\\1",$res[1]);
		return $res;
	}
	
	/**
	* @函数名:escape
	* @参数:$str-需要解码的字符串
	* @作用:php解码javascript中escape函数编码的字符串
	* @返回值:解码后的字符串
	*/
	function unescape($str) { 
	  $str = rawurldecode($str); 
	  preg_match_all("/%u.{4}|&#x.{4};|&#\d+;|.+/U",$str,$r); 
	  $ar = $r[0]; 
	  foreach($ar as $k=>$v) { 
		  if(substr($v,0,2) == "%u") 
				   $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,-4))); 
		  elseif(substr($v,0,3) == "&#x") 
				   $ar[$k] = iconv("UCS-2","utf-8",pack("H4",substr($v,3,-1))); 
		  elseif(substr($v,0,2) == "&#") { 
				   $ar[$k] = iconv("UCS-2","utf-8",pack("n",substr($v,2,-1))); 
		  } 
	  } 
	  return join("",$ar);
	}
	
	/**
	 * 查找碎片資源
	 * @param $key
	 * @param $lang
	 */
	function find_block($key,$lang=""){
		
		$cac = F("Blcok/B_".$key);
		if(empty($cac)){
			$row = M("Block")->where(array("key"=>$key))->find();
			if($row['id']){
				$list = M('block_extend')->where(array("pid"=>$row['id']))->select();
				foreach($list as $v){
					$cac[$v['lang']] = $v["value"];
				}
				F("B_".$key,$cac,DATA_PATH."Block/");
			}
		}
		$lang = empty($lang) ? getLang() : $lang ;
		return $cac[$lang];
	}
	
	/**
	 * 缓存资源
	 * @param $solevar
	 * @param $affect
	 * @param $flag(true 缓存单条记录;false 缓存多条记录)
	 */
	function save_resource($solevar,$affect,$flag=true){
		$relefile = M("Relefile");
		$map['c_solevar'] = $solevar;
		$map['c_affect']  = $affect;
		if($flag){
			$list = $relefile->where($map)->find();
		}else{
			$list = $relefile->where($map)->select();
		}
		
		F($solevar."_".$affect,$list,DATA_PATH."Resource/");
	}
	
	/**
	 * 查找单条图片缓存资源
	 * @param $solevar
	 * @param $affect
	 * @param $f
	 * @param $flag(true 单条记录;false 多条记录)
	 */
	function find_resource($solevar, $affect='single', $imgwidth=0, $imgheight=0, $array=0, $table='Product'){
		$list = F("Resource/".$solevar."_".$affect);
		
		if(empty($list)){
			save_resource($solevar,$affect,true);
			$list = F("Resource/".$solevar."_".$affect);
		}
		
		$file  = $list["fileurl"];
		if($file && $imgwidth){
			
			$path = ABS_PATH.UPLOAD_PATH;
			$url  = pathinfo($file);
			$new  = $url["dirname"]."/".$url["filename"].'_'.$imgwidth.'.'.$url["extension"];
			
			if(!file_exists($path.$new)){
				
				$oldfile = $path.$file;
				import('ORG.Util.Image');
				Image::thumb($oldfile,$path.$new,$url["extension"],$imgwidth,$imgheight);

			}
			$list["fileurl"] = $new;
		}else{
			if(!$file){
				$list["fileurl"] = "";
			}
		}
		if($array){
			return $list;
		}else{
			return $list["fileurl"];
		}
	}
	
	/**
	 * 查找多条条图片缓存资源
	 * @param $solevar
	 * @param $affect
	 * @param $f
	 * @param $flag(true 单条记录;false 多条记录)
	 */
	function find_resources($solevar,$affect='atlas',$table='Product'){
	
		$list = F("Resource/".$solevar."_".$affect);
		//dump($list);
		if(empty($list)){
			save_resource($solevar,$affect,false);
			$list = F("Resource/".$solevar."_".$affect);
		}
		return $list;
	}
	
	/**
	* @函数名:add_edit_thumb
	* @参数：$field 图片缩略图表单名; $no 资源唯一标识 ;$table 主表名称
	* @作用:添加或者修改缩略图关联表
	* @返回值:无
	*/
	function add_edit_thumb($field,$no,$table='Product'){
				
		$title    = $_POST[$field."_title"];
		$url      = $_POST[$field."_url"];
		$sort     = $_POST[$field."_sort"];
		$title    = $title[0];
		$url      = $url[0];
		$sort     = $sort[0];
		
		$relefile = M("Relefile");
		$where    = "c_solevar='$no' and c_affect='$field'";
		if(empty($url)){
			$relefile->where($where)->delete();
			return false;	
		}
		
		$record   = $relefile->where($where)->find();
		
		$data["sort"]      = $sort;
		$data["c_table"]   = $table;
		$data["c_solevar"] = $no;
		$data["c_title"]   = $title;
		$data["fileurl"]   = $url;
		$data["c_affect"]  = $field;
		$data["addtime"]   = time();

		if($record['id']){
			$data['id'] = $record['id'];
			M("Relefile")->save($data);
		}else{
			M("Relefile")->add($data);
		}
		save_resource($no,$field);
		return $data;
	}
	
	/**
	* @函数名:find_thumb
	* @参数：$no 主表唯一标识 ;$table 主表名称; $field 效果
	* @返回值:一维array
	*/
	function find_thumb($no,$field='single',$table='Product'){
		$relefile  = M("Relefile");
		$record    = $relefile->where("c_solevar='$no' and c_affect='$field'")->find();
		return $record;
	}
	
	
	/**
	* @函数名:add_edit_album
	* @参数：$field 图片缩略图表单名; $no 资源唯一标识 ;$table 主表名称
	* @作用:添加或者修改图片集关联表
	* @返回值:无
	*/
	function add_edit_album($field,$no,$table='Product'){
		$title    = I("post.".$field."_title");
		$url      = I("post.".$field."_url");
		$sort     = I("post.".$field."_sort");
		
		$where    = "c_solevar='$no' and c_affect='$field'";	
		$relefile = M("Relefile");
		$relefile->where($where)->delete();
		
		if(is_array($url)){//如果表单得到的图片，则删除该资源对应的图片集资源
			foreach($url as $k=>$v){
			  $data["c_table"]   = $table;
			  $data["c_solevar"] = $no;
			  $data["sort"]      = $sort[$k];
			  $data["c_title"]   = $title[$k];
			  $data["fileurl"]   = $v;//substr_replace($v,"",0,strlen(UPLOAD_URL));
			  $data["c_affect"]  = $field;
			  $data["addtime"]   = time();
			  M("Relefile")->add($data);
		  }
		  save_resource($no,$field,false);
		}
	}
	
	/**
	 * @函数名:find_album
	 * @参数：$no 主表唯一标识 ;$table 主表名称; $field 效果
	 * @返回值:二维array
	 */
	function find_album($no,$field='atlas',$table='Product'){
		$relefile  = M("Relefile");
		$record    = $relefile->where("c_solevar='$no' and c_affect='$field'")->select();
		return $record;
	}
	
	/**
	 * @函数名:find_file
	 * @参数：$no 主表唯一标识 ;$table 主表名称; $field
	 * @返回值:一维array
	 */
	function find_file($no,$field='attach',$table='Product'){
		$relefile  = M("Relefile");
		$record    = $relefile->where("c_solevar='$no' and c_affect='$field'")->select();
		return $record;
	}
	
	
	/**
	 * @函数名:add_edit_file
	 * @参数：$field 文件表单名; $no 资源唯一标识 ;$table 主表名称
	 * @作用:添加或者修改文件关联表
	 * @返回值:无
	 */
	function add_edit_file($field,$no,$table='Product'){
		$title    = I("post.".$field."_title");
		$url      = I("post.".$field."_url");
	
		$where    = "c_solevar='$no' and c_affect='$field'";
		$relefile = M("Relefile");
		$relefile->where($where)->delete();
	
		if(is_array($url)){//如果表单得到的图片，则删除该资源对应的图片集资源
			foreach($url as $k=>$v){
				$data["c_table"]   = $table;
				$data["c_solevar"] = $no;
				$data["c_title"]   = $title[$k];
				$data["fileurl"]   = substr_replace($v,"",0,strlen(UPLOAD_URL));
				$data["c_affect"]  = $field;
				$data["addtime"]   = time();
				M("Relefile")->add($data);
			}
			save_resource($no,$field,false);
		}
	}
	
	/**
	* @函数名:create_option_array
	* @参数:$arr-数组
	* @参数:$id,$value,$default 默认值
	* @作用:把数组生成select
	* @返回值:html字符串
	*/
	function create_option_array($arr=array(),$id,$value,$default=-1,$lang=false){
		$html = '';
		foreach($arr as $v){
			$v[$value] = $lang ? L($v[$value]) : $v[$value];
			if($v[$id] == $default){
				$html .= '<option value="'.$v[$id].'" selected>'.$v[$value].'</option>';
			}else{
				$html .= '<option value="'.$v[$id].'">'.$v[$value].'</option>';	
			}
		}
		return $html;
	}
	
	/**
	* @函数名:create_option_key
	* @参数:$arr-数组
	* @参数:$id,$value,$default 默认值
	* @作用:把数组生成select
	* @返回值:html字符串
	*/
	function create_option_key($arr=array(),$default=0,$lang=false){
		$html = '';
		foreach($arr as $k=>$v){
			$v = $lang ? L($v) : $v;
			if( $k == $default){
				$html .= '<option value="'.$k.'" selected>'.$v.'</option>';
			}else{
				$html .= '<option value="'.$k.'">'.$v.'</option>';	
			}
		}
		return $html;
	}
	
	//根据健得到对应数组的值
	function get_array_key($array,$key,$lang=false){
		$value = '';
		if(is_string($array)){
			$array = C("$array");
		}
		foreach($array as $k=>$v){
			if($k==$key){
				$value = $lang ? L($v) : $v ;
				break;
			}	
		}
		return $value;
	}
	
	//得到数组的select
	function get_cate_select($arr,$fid,$nid,$prefix=''){
		$html = '';
		if(is_array($arr)){
			foreach($arr as $k=>$v){
				if($v['pid']==$fid) {
					if($nid==$v['id']){
						$html .= "<option value=\"".$v['id']."\" selected>".$prefix." ".$v['title']."</option>";
					}else{
						$html .= "<option value=\"".$v['id']."\">".$prefix." ".$v['title']."</option>";
					}
					$html .= get_cate_select($arr,$v['id'],$nid,$prefix."—");
				}
			}
		}
		return $html;
	}
	
	/**
	 * 得到缓存中的系统配置参数 
	 */
	function get_syscfig_key($key,$type=''){
		
		$array = F('Sysconfig');
		$value = $array['cfg'][$key];
		if($type){
			$value = $value[$type];
		}
		$value = str_replace('\n','<br/>',$value);
		return $value;
	}
	
	/*
	 * 从缓存中读取栏目和分类的数组
	* @parma $lang   语言版本
	* @param $module 模型
	* @type  $缓存类型
	*/
	function get_cate_array($lang,$module='',$type='cate'){
		$array = F($type."_".$lang.$module);
		return $array;
	}
	
	//创建栏目UL的数组
	function create_cate_array($array,$pid,$nid){
		$_temp = array();
		foreach($array as $v){
			if($v["pid"]==$pid) {
				$v['url'] = create_front_url($v,"");
				$_temp[] = $v ;
				$_row = create_cate_array($array,$v['id'],$nid);
				if(count($_row)){
					foreach($_row as $k){
						$_temp[] = $k ;
					}
				}
			}
		}
		return $_temp;
	}
	
	//创建栏目UL的html
	function create_cate_html($array,$pid,$nid,$delim=true,$action='',$aclass='',$lclass='',$id=''){
		$html = '';
		$i    = 0;
		foreach($array as $v){
			if($v["pid"]==$pid) {
				if($i&&$delim){
					$html .= '<li class="line">&nbsp;</li>';
				}
				$url = create_front_url($v,$action);
	
				$lc  = empty($lclass) ? "" : $lclass.$v['level'] ;
				$idc = empty($id)     ? "" : $id.$v['id']    ;
				if($v["id"] == $nid) {
					$html .= '<li class="hover '.$aclass.$lc.'" id="'.$idc.'">
							  <a href="'.$url.'" title="'.$v["title"].'" >'.$v["title"].'</a>';
				}else{
					$html .= '<li class="link  '.$aclass.$lc.'" id="'.$idc.'">
					          <a href="'.$url.'" title="'.$v["title"].'" >'.$v["title"].'</a>';
				}
				$i++;
				$html .= create_cate_html($array,$v['id'],$nid,$delim,$action,$aclass,$lclass,$id);
				$html .= '</li>';
			}
		}
		if(!empty($html)){
			$html = '<ul>'.$html.'</ul>';
		}
		return $html;
	}
	
	//创建栏目UL的html
	function create_top_html($array,$pid,$nid,$delim=true,$action='',$aclass='',$lclass='',$id=''){
		$html = '';
		$i    = 0;
		foreach($array as $v){
			if($v["pid"]==$pid) {
				if($i&&$delim){
					$html .= '<li class="line">&nbsp;</li>';
				}
				$url = create_front_url($v,$action);
	
				$lc  = empty($lclass) ? "" : $lclass.$v['level'] ;
				$idc = empty($id)     ? "" : $id.$v['id']    ;
				if($v["id"] == $nid) {
					$html .= '<li class="hover '.$aclass.$lc.'" id="'.$idc.'">
							  <a href="'.$url.'" title="'.$v["title"].'" >'.$v["title"].'</a>';
				}else{
					$html .= '<li class="link  '.$aclass.$lc.'" id="'.$idc.'">
					          <a href="'.$url.'" title="'.$v["title"].'" >'.$v["title"].'</a>';
				}
				$i++;
				//$html .= create_cate_html($array,$v['id'],$nid,$delim,$action,$aclass,$lclass,$id);
				$html .= '</li>';
			}
		}
		return $html;
	}
	
	//根据栏目ARRAY获取对应的URL
	function create_front_url($v,$action=''){
		$front = C("FRONT_URL");
		$base  = $front;
		$flag  = true ;
		if($v['handurl']){
			$flag  = false ;
			$url   = $v['handurl'];
			$pattern = '/(http|https|ftp|file){1}(:\/\/)?([\da-z-\.]+)\.([a-z]{2,6})([\/\w \.-?&%-=]*)*\/?/';
			if(!preg_match($pattern,$url)){
				$flag  = true ;
			}
		}else{
			if($v['url']){
				$url = $v['url'];
			}else{
				$url = "Index/index";
			}
		}
		if($flag){
			$url = create_url($url,$action,$v['id']);
		}
	
		return $url;
	}
	
	//根据url获取网站链接
	function get_front_url($url){
		$front = C("FRONT_URL");
		$base  = $front;
		$pattern = '/(http|https|ftp|file){1}(:\/\/)?([\da-z-\.]+)\.([a-z]{2,6})([\/\w \.-?&%-=]*)*\/?/';
		if(!preg_match($pattern,$url)){
			$url = create_url($url);
		}
		return $url;
	}
	
	//生成URL
	function create_url($url,$action='',$cateid=''){
		$uarr   = explode("/",$url);
		$module = array_shift($uarr);
		$doact  = array_shift($uarr);
		if($action){
			$doact = $action;
		}
		$url   = $module."/".$doact;
		$param = "";
		if(count($uarr)){
			foreach($uarr as $k=>$v){
				if($k%2){
					$param .= $v;
				}else{
					$param .= "&".$v."=";
				}
			}
		}else{
			if($cateid){
				$param .= 'cateid='.$cateid ;
			}
		}
		return U($url,$param);
	}
	
	//得到当前位置
	function get_cate_position($cateid,$class='',$did,$action='',$type="cate"){
		$lang  = getLang();
		$array = get_cate_array($lang,'',$type);
		return get_cate_position_func($cateid,$class,$array,$did,$action);
	}
	
	//得到当前位置(递归)
	function get_cate_position_func($cateid,$class,$arr,$did=0,$action=''){
		$title    = '';
		$fatherId = 0;
		foreach($arr as $li){
			if($cateid==$li['id']){
				$url   = create_front_url($li,$action);
				$title = '<li><a href="'.$url.'">'.$li['title'].'</a></li>';
				if($did != $li['id']){
					$title .= '<li><i class="'.$class.'"></i></li>';
				}		 
				$fatherId = $li['pid'];break;
			}
		}
		if($fatherId){
			$title = get_cate_position_func($fatherId,$class,$arr,$action).$title;
		}
		return $title;
	}
	
	//读取栏目分类，根据不同条件
	function get_cate_by_param($lang,$module='',$param){
		$array = get_cate_array($lang,$module);
		$rows  = array();
		$i     = 0;
		foreach($array as $k=>$v){
			$flag = true ;
			foreach($param as $a=>$b){
				if($v[$a]!=$b){
					$flag = false;
					break;
				}
			}
			if($flag){
				$rows[$i] = $v;
				$i++;
			}
		}
		return $rows;
	}
	
	/*
	 * 找到根父级id
	* @parma $type cate为栏目 colum为分类
	*/
	function sonFindFather($id,$type="cate"){
		$lang  = getLang();
		$array = get_cate_array($lang,'',$type);
		return sonFindFather_func($id,$array);
	}
	
	/*
	 * 根据条件找到根父级id
	* @parma $type cate为栏目 colum为分类
	* @map   查找条件 array("level"=>1,"pid"=>1)
	*/
	function sonFindFatherByMap($id,$map=NULL,$type="cate"){
		$lang  = getLang();
		$array = get_cate_array($lang,'',$type);
		return sonFindFather_func($id,$array,$map);
	}
	
	/*
	 * 找到子级id组成的字符串
	* @parma $type cate为栏目 colum为分类
	*/
	function fatherFindChilds($id,$type="cate"){
		$lang  = getLang();
		$array = get_cate_array($lang,'',$type);
		return fatherFindChilds_func($id,$array);
	}
	
	/*
	 * 找到子级id组成的字符串-无语言版本
	* @parma $type cate为栏目 colum为分类
	*/
	function fatherFindChildsArr($id,$type="cate"){
		$array = F($type);
		//dump($array);
		return fatherFindChilds_func($id,$array);
	}
	
	//找到根父级id
	function sonFindFather_func($id,$array){
		$father = $id;
		foreach($array as $v){
			if($v['id']==$id){
				if($v['pid']){
					$father = sonFindFather_func($v['pid'],$array);
				}
			}
		}
		return $father;
	}
	
	//找到根父级id
	function sonFindFatherByMap_func($id,$array,$map){
		$father = $id;
		foreach($array as $v){
			if(is_array($map)){
				$flag = true;
				foreach($map as $a=>$b){
					if($v[$a]!=$b){
						$flag = false;break;
					}
				}
				if($flag){
					return $id;
				}
			}
			if($v['id']==$id){
				if($v['pid']){
					$father = sonFindFatherByMap_func($v['pid'],$array);
				}
			}
		}
		return $father;
	}
	
	//找到子级id组成的字符串
	function fatherFindChilds_func($fid,$array){
		$str = $fid;
		foreach($array as $row){
			if($row["pid"] == $fid){
				$str_child = fatherFindChilds_func($row["id"],$array);
				if($row["id"] == $str_child){
					$str .= ",".$row["id"];
				}else{
					$str .= ",".$str_child;
				}
			}
		}
		return $str;
	}
	
	/**
	 * 对数组和标量进行 urlencode 处理
	 * 通常调用 php_urlencode()
	 * 处理 json_encode 中文显示问题
	 * @param array $data
	 * @return string
	 */
	function php_urlencode($data) {
		if (is_array($data) || is_object($data)) {
			foreach ($data as $k => $v) {
				if (is_scalar($v)) {
					if (is_array($data)) {
						$data[$k] = urlencode($v);
					} else if (is_object($data)) {
						$data->$k = urlencode($v);
					}
				} else if (is_array($data)) {
					$data[$k] = php_urlencode($v); //递归调用该函数
				} else if (is_object($data)) {
					$data->$k = php_urlencode($v);
				}
			}
		}
		return $data;
	}
	
	/**
	 * json 编码
	 * 解决中文经过 json_encode() 处理后显示不直观的情况
	 * 如默认会将“中文”变成"\u4e2d\u6587"，不直观
	 * 如无特殊需求，并不建议使用该函数，直接使用 json_encode 更好，省资源
	 * json_encode() 的参数编码格式为 UTF-8 时方可正常工作
	 *
	 * @param array|object $data
	 * @return array|object
	 */
	function ch_json_encode($data) {
		$ret = php_urlencode($data);
		$ret = json_encode($ret);
		return urldecode($ret);
	}
	
	/**
	 * google api 二维码生成【QRcode可以存储最多4296个字母数字类型的任意文本，具体可以查看二维码数据格式】
	 * @param string $chl 二维码包含的信息，可以是数字、字符、二进制信息、汉字。不能混合数据类型，数据必须经过UTF-8
	 URL-encoded.如果需要传递的信息超过2K个字节，请使用POST方式
	 * @param int $widhtHeight 生成二维码的尺寸设置
	 * @param string $EC_level 可选纠错级别，QR码支持四个等级纠错，用来恢复丢失的、读错的、模糊的、数据。
	 *                         L-默认：可以识别已损失的7%的数据
	 *                         M-可以识别已损失15%的数据
	 *                         Q-可以识别已损失25%的数据
	 *                         H-可以识别已损失30%的数据
	 * @param int $margin 生成的二维码离图片边框的距离
	 */
	function erweima($chl,$widhtHeight ='150',$EC_level='L',$margin='0') {
		$chl = urlencode($chl);
		$erweima = '<img src="http://chart.apis.google.com/chart?chs='.$widhtHeight.'x'.$widhtHeight.'&cht=qr&chld='.$EC_level.'|'.$margin.'&chl='.$chl.'" alt="QR code" widhtHeight="'.$widhtHeight.'" widhtHeight="'.$widhtHeight.'"/>';
		return $erweima;
	}
	
	/**
	 * 获取积分规则
	 */
	function getIntegralType(){
		$integral = C("CONF_INTEGRAL_TYPE");
		return $integral;
	}
	
	/**
	 * 使用场景验证
	 * @param string $sence_name 场景名称
	 * @param string $url   跳转url（没有可抽奖的活动、优惠券）
	 * @param string $mtype 返回类型：ACTIVE-抽奖、YHJ-优惠劵
	 * @param string $rtype 返回类型：1-页面跳转、2-布尔值
	 * @return array|object
	 */
	function sence_check($sence_name,$mtype,$rtype=1,$now) {
		if($mtype=='ACTIVE'){
			$model_name = 'Actlottery';
		}elseif($mtype=='YHJ'){
			$model_name = 'Actyhj';
		}
		
		$model = M($model_name);
		$map = array(
			'sence_use' => 1,
			'sence' => $sence_name
		);
		$data = $model->where($map)->find();
		
		$bool = false;
		
		if($data['id']){
			$bool = true;
		}
		
		$config = C('SENCE_'.$mtype);
		if($rtype==1&&$bool){
			if($mtype=="ACTIVE"){
				$now->success(L($config[$sence_name][1]),U($config[$sence_name][2].$data['type'],"id=".$data['id']));
				exit();
			}else{
				$now->success(L($config[$sence_name][1]),U($config[$sence_name][2],"id=".$data['id']));
				exit();
			}
		}elseif($rtype==2){
			return $bool;
		}else{
			return $bool;
		}
	}
	
	/**
	 * 根据ip获取当前城市信息
	 */
	function getCityInfo(){
		
		//上海 114.80.166.240
		//北京 58.30.16.0
		//广州 219.137.148.0
		//顺义 
		//长沙 222.244.205.63
		
		$ip   = get_client_ip();
		$path = "http://ip.taobao.com/service/getIpInfo.php?ip=".$ip;
		//$path = "http://ip.taobao.com/service/getIpInfo.php?ip=221.217.77.191";
		
		$data = json_decode(file_get_contents($path),true);
		return $data['data'];
	}
	
	/**
	 * 根据时间戳计算分钟数
	 */
	function getminus($time){
		return ceil($time/60);
	}
	
	function addressJsonEncode($map){
		foreach($map as $k=>$v){
			$map[$k] = urlencode($v);
		}
		cookie(C('USER_SELECT_CITY'),json_encode($map),'3600');
		
	}
	
	function addressJsonDecode(){
		$map = json_decode((stripslashes(cookie(C('USER_SELECT_CITY')))),true);
		foreach($map as $k=>$v){
			$map[$k] = urldecode($v);
		}
		return $map;
	}
	
	function getaddresscity($city,$lang=''){
		$array = C('CITYID');
		
		if(empty($lang)){
			$lang  = getLang();
		}
		
		$num   = $lang=='zh-cn'?1:'0';
		if($city){
			return $array[$city][$num];
		}else{
			return "";
		}
	}
?>